import {UserRepository} from '../repository/user';
import {User} from '../entity/user';
import {getRepository} from "typeorm";
import {SyncData} from "../entity/sync";

import {WebUSB, webusb} from "usb/dist";
import {io} from "socket.io-client";

var net = require('net');
// import syncUtil from "../util/syncUtil";

// 获取存储库
// @Injectable()
class SyncService {

    private userRepository: UserRepository;

    constructor() {
        // this.userRepository = new UserRepository(User, manager);
        this.userRepository = getRepository(User);
    }

    async findAll(): Promise<SyncData[]> {

        console.log("===============+>"); // Legacy device
        return (async () => {
            const result: SyncData[] = []
            // Returns first matching device
            const customWebUSB = new WebUSB({
                // Bypass checking for authorised devices
                allowAllDevices: true
            });

            // Uses blocking calls, so is async
            const devices = await customWebUSB.getDevices();

            devices.forEach((device, index) => {
                // console.log(device); // WebUSB device
                const syncData = new SyncData();
                syncData.id = index
                syncData.manufacturerName = device.manufacturerName
                syncData.productName = device.productName
                syncData.serialNumber = device.serialNumber
                syncData.ip = "127.0.0.1"
                syncData.port = "7000"
                result.push(syncData)
            })
            return result
        })();

        // return this.userRepository.find({
        //     relations: {
        //         tasks: true,
        //     }
        // });
    }


    async update(id: number, data: object): Promise<any | undefined> {
        const result: SyncData[] = []

        const ip = "255.255.255.255"
        // const ip = "127.0.0.1"
        const port = "7000"

        const socket = io(`${ip}:${port}`);
        return (async () => {

            this.syncSocket(data)
            // this.syncNetSocket(data)

            return result
        })();
    }

    syncNetSocket(data): void {
        var port = 7000;
        var host = '127.0.0.1';
        // const host = '255.255.255.255'

        var client = new net.Socket();
        client.setEncoding('utf8');
        client.connect(port, 'localhost', function () {
            console.log('已连接到服务器端。');
            client.write("{'msg': \"你好。\"}");
        });
        client.on('data', function (data) {
            console.log('已接收服务器端发送的数据：' + data);
        });
    }

    syncSocket(data): void {

        // const ip = "192.168.0.110"
        const ip = "127.0.0.1"
        const port = "7000"

        const socket = io("wss://127.0.0.1:7000");
        console.log('socket==>', socket)
        socket.on("connect", () => {
            console.log("connect==>", socket.connected); // true
            const engine = socket.io.engine;
            console.log(engine.transport.name); // in most cases, prints "polling"

            engine.once("upgrade", () => {
                // called when the transport is upgraded (i.e. from HTTP long-polling to WebSocket)
                console.log(engine.transport.name); // in most cases, prints "websocket"
            });

            engine.on("packet", ({type, data}) => {
                // called for each packet received
            });

            engine.on("packetCreate", ({type, data}) => {
                // called for each packet sent
            });

            engine.on("drain", () => {
                // called when the write buffer is drained
            });

            engine.on("close", (reason) => {
                // called when the underlying connection is closed
            });
        });
        socket.on("connect_error", () => {
            console.log('connect_error-1')
        });

        socket.io.on("error", (error) => {
            console.log('connect_error-2', error)
        });


        socket.on("data", () => {
            console.log("data==>", socket.connected); // true
            socket.emit("hello", "world");
        });

        socket.timeout(5000).emit("PC同步数据：", JSON.stringify(data), (err: any, responses: any) => {
            if (err) {
                // some clients did not acknowledge the event in the given delay
            } else {
                console.log(responses); // one response per client
            }
        });

        socket.on("disconnect", () => {
            console.log(socket.connected); // false
        });

    }

    async openSync(): Promise<any | undefined> {
        return (async () => {
            var server = net.createServer();
            server.on('connection', function (socket) {
                console.log('客户端与服务器端连接已建立。');
                socket.setEncoding('utf8');
                socket.on('data', function (data) {
                    console.log('已接收客户端发送的数据：' + data);
                    socket.write('确认数据：' + data);
                });
                socket.on('error', function (err) {
                    console.log('与客户端通信的过程中发生了一个错误，错误编码为%s。', err.code);
                    socket.destroy();
                });
                socket.on('end', function () {
                    console.log(' 客户端连接被关闭。');
                    server.unref();
                });
                socket.on('close', function (had_error) {
                    if (had_error) {
                        console.log('由于一个错误导致socket端口被关闭。');
                        server.unref();
                    } else
                        console.log('socket端口被正常关闭。');
                });
                server.getConnections(function (err, count) {
                    if (count == 2)
                        server.close();
                });
            });
            server.listen(7000, 'localhost');
            server.on('close', function () {
                console.log('TCP服务器被关闭。');
            });

            console.log('准备开启同步服务成功。。。。。。。')
        })();
    }
}

export default SyncService;
